<?php

/**
 * Description of ArticleModel
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
final class ArticleModel extends Article {

    /**
     * The constructor.
     */
    public function __construct(array $fields = array()) {
        parent::__construct($fields);
    }

    /**
     * ADMIN SPECIFIC METHODS.
     */

    /**
     * Getting data for all articles within a given panel.
     * Returns paginated results in descending order.
     *
     * @param int $panelId
     * @param int $pageNumber
     * @return array
     */
    public static function getArticleData($panelId, $searchString = NULL, $pageNumber = 1) {

        /**
         * Get paginated results.
         */
        $queryCount = new Query('
            SELECT COUNT(*) AS `count`
            FROM `article`
            :where
            :and :search;
        ');
        $queryCount = AdminUtils::queryProcessing($queryCount, 'article', 'panel', $panelId, $searchString);
        $query = new Query('
            SELECT :select
            FROM `article`
            :bridge
            :join
            :where
            :and :search
            ORDER BY `z`.`panel` DESC, `article`.`id`
            LIMIT :offset, :row_count;
        ');
        $query = AdminUtils::queryProcessing($query, 'article', 'panel', $panelId, $searchString);

        $pagination = new Pagination(
            $query,
            $queryCount,
            $pageNumber
        );
        $output = array();
        $output['tabulated'] = $pagination->getRows();
        $output['navigation_array'] = $pagination->getNavigationArray();
        
        /**
         * Get array data for each article.
         */
        foreach ($output['tabulated'] as $key => $articleArray) {
            $article = new Article;
            $article->load($articleArray['id']);
        
            /**
             * Get media data.
             */
            $media = $article->getMedia();
            if (count($media) > 0) {
                $output['tabulated'][$key]['media'] = array();
                foreach ($media as $mediumKey => $medium) {                
                    $output['tabulated'][$key]['media'][$mediumKey] = $medium->getViewFields();
                }
            }
        
            /**
             * Get HTML form data.
             */
            $htmlForms = $article->getHtmlForms();            
            if (count($htmlForms) > 0) {
                $output['tabulated'][$key]['html_forms'] = array();
                foreach ($htmlForms as $htmlFormKey => $htmlForm) {                
                    $output['tabulated'][$key]['html_forms'][$htmlFormKey] = $htmlForm->getViewFields();
                }
            }
            
        }

        /**
         * Get panel data.
         */
        if ($panelId != NULL) {
            $panel = new Panel;
            $panel->load($panelId);
            $output['panel'] = $panel->getViewFields();
        }

        return $output;
    }

}